package cn.rocky.offer;

/**
 * @author viki
 * @version 1.0
 * @description 剑指offer25 输入两个递增排序的链表，合并这两个链表并使新链表中的节点仍然是递增排序的。
 * 输入：1->2->4, 1->3->4
 * 输出：1->1->2->3->4->4
 * @date 2021/7/9 9:03
 */
class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

/**
 * 一些方法
 *
 * @author Rocky
 */
class Solution {
    /**
     * 合并排序
     *
     * @param l1 l1
     * @param l2 l2
     * @return
     */
    ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dum = new ListNode(0);
        ListNode cur = dum;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        cur.next = l1 != null ? l1 : l2;
        return dum.next;
    }

    /**
     * 打印结点
     *
     * @param l1
     */
    void printListNode(ListNode l1) {
        while (l1 != null) {
            System.out.print(l1.val);
            if (null != l1.next) {
                System.out.print("->");
            }
            l1 = l1.next;
        }
    }


}

/**
 * @author Rocky
 */
public class MergeTwoLists {
    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode l1 = new ListNode(0);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(3);
        System.out.print("l1的节点: ");
        solution.printListNode(l1);
        System.out.println();
        ListNode l2 = new ListNode(0);
        l2.next = new ListNode(1);
        l2.next.next = new ListNode(2);
        System.out.print("l2的节点: ");
        solution.printListNode(l2);
        System.out.println();
        System.out.print("合并且排序好的listNode: ");
        ListNode listNode = solution.mergeTwoLists(l1, l2);
        solution.printListNode(listNode);
    }
}





